package org.pz.job;

import lombok.extern.slf4j.Slf4j;
import org.pz.component.ScheduleTaskCollections;
import org.pz.task.BaseSchedulerTask;
import org.pz.utils.TaskUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * 用来执行 bean 的 job，内部通过 JobDataMap 中的数据来查找一个已存在的 bean 作为执行方法
 * */
@Slf4j
public class BeanTaskJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String jobName = context.getJobDetail().getKey().getName();
        log.info( "定时任务 {} 执行开始", jobName );

        ScheduleTaskCollections col = (ScheduleTaskCollections) context.getMergedJobDataMap().get(TaskUtil.SCHEDULE_TASKS);
        if(col == null){
            throw new JobExecutionException("定时任务执行异常【配置信息为空】");
        }

        BaseSchedulerTask job = col.findTaskClassByValue(context.getMergedJobDataMap().get(TaskUtil.JOB_CODE).toString());
        if(job == null){
            throw new JobExecutionException("定时任务执行异常【获取指定 code 失败】");
        }

        //执行方法
        try {
            job.execute();
        }catch (Exception e){
            log.info("定时任务执行异常【任务内部异常】:{}", e.getMessage());
        }


        log.info( "定时任务 {} 执行结束", jobName );
    }
}
